package com.noble.library.time;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.noble.library.basic.log.PLogger;

import java.util.Calendar;

/**
 * 定时工具类
 */
public class TimerUtil {

    public interface CallBack {
        void call();
    }

    /**
     * 延时执行
     *
     * @param callBack 延时执行回调
     * @param tm       延时时长
     */
    public static void beginTime(final CallBack callBack, int tm) {
        final Handler handler = new Handler();
        Runnable runnable = () -> callBack.call();
        handler.postDelayed(runnable, tm);
    }

    /**
     * 启动一个循环定时器，默认是针对Service的。
     *
     * @param time 时间间隔。
     */
    public static void startRepeatTimer(Context context, Intent intent, long time) {
        if (intent == null) return;

        try {
            Calendar calendar = Calendar.getInstance();
            long firstTime = calendar.getTimeInMillis() + time;

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, time, pendingIntent);
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    /**
     * 取消一个闹钟，默认是针对Service的。
     */
    public static void cancelTimer(Context context, Intent intent) {
        if (intent == null) return;

        try {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pendingIntent);
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    // ============================================ 长连接 =======================================
    private static int increaseTimeCount = 0;

    /**
     * 获取在上下区间以最小值进行递增的数值，达到最大值时重置
     *
     * @param minTime 最小值
     * @param maxTime 最大值
     * @param reset   是否立即重置
     * @return 递增的数值
     */
    public static int increaseTime(int minTime, int maxTime, boolean reset) {
        if (reset) increaseTimeCount = 0;
        increaseTimeCount += minTime;
        if (increaseTimeCount > maxTime) increaseTimeCount = minTime;
        return increaseTimeCount;
    }

    /**
     * 重置递增数值
     */
    public static void resetIncreaseTime() {
        increaseTimeCount = 0;
    }

}
